import React, { Component } from 'react';
import {
	StyleSheet, Alert, Text, View, Image, Dimensions, TouchableOpacity, DeviceEventEmitter,
	Platform
} from "react-native";
import { style } from '../../theme/style';
import { GLOBAL } from '../../config/global';
import { STORAGE_CONSTANT } from '../../config/storage';
import { API, API_GENERATE } from '../../config/api';
import { HxActionSheet } from '../../component/HxActionSheet';
import { Common } from '../../component/common/Common';
import { ENVIRONMENT } from '../../config/env';
import HTTP from '../../utils/http';
import ToastUtils from '../../utils/toast';
import StorageHelper from '../../utils/storageHelper';
import Dictionary from '../../utils/dictionary';
import * as Keychain from 'react-native-keychain';

import { StackActions, NavigationActions } from 'react-navigation';

const resetAction = StackActions.reset({
	index: 0,
	actions: [NavigationActions.navigate({ routeName: 'LoginPage' })],
});

const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;
const envStatus = {
	'1': 'DEV',
	'2': 'TEST',
	'3': 'UAT',
	'4': 'PREP',
	'5': 'ZHDS',
	'6': 'PROD'
}
const envStatusProd = {
	'1': 'PROD',
	'2': 'ZHDS'
}


export class UserSetPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '设置',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../imgs/goBackEmpty.png')} />),
			headerStyle: {
				elevation: 0,
				backgroundColor: style.color.themeColor,
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props)
		this.onPressModalButton = this.onPressModalButton.bind(this);
		this.onPressSetUp = this.onPressSetUp.bind(this);
		this.actionSheetPress = this.actionSheetPress.bind(this);
		this.state = {
			current_env_title: ENVIRONMENT[GLOBAL.CURR_ENV].title
		}
	};

	async componentWillMount() {
		const appVersionInfo = await StorageHelper.get(STORAGE_CONSTANT.APP_VERSION_INFO);
		if (JSON.parse(appVersionInfo)) {
			this.appVersionInfo = JSON.parse(appVersionInfo);
		} else {
			this.appVersionInfo = await HTTP.GET(API_GENERATE(API.GET_UPDATE_INFO), { suitPlatform: Platform.OS }, {
				rejectError: true,
				handleError: false
			});
			StorageHelper.set(STORAGE_CONSTANT.APP_VERSION_INFO, this.appVersionInfo);
		}
	}

	switchEnviromentSelect() {
		this.SwitchActionSheet.onShowCustomActionSheet();
	}

	async switchEnviroment(env) {
		if (!env) {
			return
		} else if (env == GLOBAL.CURR_ENV) {
			Alert.alert(`当前就是${ENVIRONMENT[env].title}环境~`);

		} else {
			await StorageHelper.set(STORAGE_CONSTANT.CURR_ENV, env);
			GLOBAL.CURR_ENV = env;
			this.setState({
				current_env_title: ENVIRONMENT[GLOBAL.CURR_ENV].title
			})
			DeviceEventEmitter.emit('current_env', env)
			this.actionSheetPress(1, true)
		}
	}

	onPressModalButton() {
		this.HxActionSheet.onShowCustomActionSheet();
		// let username = '';
		// let password = '';
		// Keychain.setGenericPassword(username, password);
		GLOBAL.isFingerprintStatus = false;
	}

	async clearStorage() {
		await StorageHelper.remove(STORAGE_CONSTANT.CURR_ENV);
		ToastUtils.showSuccess(`清除成功,请重新登录~`).then(() => {
			this.actionSheetPress(1);
		})
	}

	async actionSheetPress(index, logout) {
		if (index == 1) {
			//退出登录
			await StorageHelper.multiRemove([
				STORAGE_CONSTANT.DICTIONARY,
				STORAGE_CONSTANT.VERSION_IGNORE,
				STORAGE_CONSTANT.TOKEN,
				STORAGE_CONSTANT.MODULE_VERSION,
				STORAGE_CONSTANT.CONST_INFO,
				STORAGE_CONSTANT.CONST_INFO_EXPIRE
				// STORAGE_CONSTANT.BIND_BIOMETRY_AUTH,
			])
			let res = await HTTP.POST(API_GENERATE(API.LOG_OUT));
			if (res || logout) {
				GLOBAL.TOKEN = null;
				GLOBAL.LOGIN_NAME = null;
				ToastUtils.showInfo('正在退出...').then(() => {
					GLOBAL.ROOT_NAVIGATION.dispatch(resetAction);
				})
			}
		}
	}

	onPressSetUp() {
		this.props.navigation.navigate('safeSetting');
	}

	//更新数据字典
	_upDictionary = async () => {
		await Dictionary.updated();
		ToastUtils.showSuccess(`数据字典更新成功`);
	}

	render() {
		const { params } = this.props.navigation.state;
		return (
			<View style={styles.container}>
				<View style={[styles.listBox, styles.listBoxActive]}>
					<TouchableOpacity style={[styles.list]} onPress={() => { this.props.navigation.navigate('AboutUsPage', { appVersionInfo: this.appVersionInfo, appHasUpdate: params }) }} activeOpacity={1} >
						<Text style={styles.listLeft}>关于我们</Text>
						<View style={styles.listRight}>
							{params ? (<Text style={styles.listRightText}>有更新</Text>) : (null)}
							<Image style={styles.listRightImg} source={require('../../imgs/arrow-left.png')} />
						</View>
					</TouchableOpacity>
					<TouchableOpacity style={[styles.list]} onPress={() => { this.clearStorage() }} activeOpacity={1} >
						<Text style={styles.listLeft}>清除缓存</Text>
					</TouchableOpacity>
					<TouchableOpacity style={[styles.list, styles.listActive]} onPress={() => { this._upDictionary() }} activeOpacity={1} >
						<Text style={styles.listLeft}>更新数据字典</Text>
					</TouchableOpacity>
				</View>
				{
					ENVIRONMENT[GLOBAL.CURR_ENV].switchEnable ?
						<View>
							<View style={styles.enviroment} >
								<Text style={styles.enviromentText}>当前是{this.state.current_env_title}</Text>
							</View>
							<TouchableOpacity style={styles.switchEnviromentButton} onPress={() => { this.switchEnviromentSelect() }}  >
								<Text style={styles.logOutText}>切换环境</Text>
							</TouchableOpacity>
							{
								(GLOBAL.CURR_ENV === 'PROD' || GLOBAL.CURR_ENV === 'ZHDS') ?
									<HxActionSheet
										ref={o => this.SwitchActionSheet = o}
										title={<View><Text style={styles.actionTitle}>注意：切换环境后需要重新登陆</Text></View>}
										titleIOS={'注意：切换环境后需要重新登陆'}
										options={['取消', <Text style={styles.sheetTextColor}>切换中化化销</Text>, <Text style={styles.sheetTextColor}>切换中化电商</Text>]}
										optionsIOS={['取消', '中化化销', '中化电商']}
										onPress={(i) => {
											this.switchEnviroment(envStatusProd[i]);
										}}
										destructiveButtonIndex={9}
										styles={{
											titleBox: {
												height: 63 * scale,
												marginBottom: 1 * scale
											}
										}}
									/> :
									<HxActionSheet
										ref={o => this.SwitchActionSheet = o}
										title={<View><Text style={styles.actionTitle}>注意：切换环境后需要重新登陆</Text></View>}
										titleIOS={'注意：切换环境后需要重新登陆'}
										options={['取消', <Text style={styles.sheetTextColor}>切换开发环境</Text>, <Text style={styles.sheetTextColor}>切换UAT环境</Text>, <Text style={styles.sheetTextColor}>切换测试环境</Text>, <Text style={styles.sheetTextColor}>切换油销演示环境</Text>]}
										optionsIOS={['取消', '切换开发环境', '切换测试环境', '切换UAT环境', '切换油销演示环境']}
										onPress={(i) => {
											this.switchEnviroment(envStatus[i]);
										}}
										destructiveButtonIndex={9}
										styles={{
											titleBox: {
												height: 63 * scale,
												marginBottom: 1 * scale
											}
										}}
									/>
							}

						</View> : null
				}
				{/* {GLOBAL.SUPPORT_BIOMETRY_TYPE ? ( */}
				<View>
					<TouchableOpacity style={styles.logOut} onPress={this.onPressSetUp} activeOpacity={1} >
						<Text style={styles.logOutText}>安全设置</Text>
					</TouchableOpacity>
				</View>
				{/* ) : null} */}

				<View>
					<TouchableOpacity style={styles.logOut} onPress={this.onPressModalButton} activeOpacity={1} >
						<Text style={styles.logOutText}>退出登录</Text>
					</TouchableOpacity>
					<HxActionSheet
						ref={o => this.HxActionSheet = o}
						title={<View><Text style={styles.actionTitle}>退出后不会删除任何历史数据，下次登录依然可以使用本账号</Text></View>}
						titleIOS={'退出后不会删除任何历史数据，下次登录依然可以使用本账号'}
						options={['取消', <Text style={styles.logOutTextColor}>退出登录</Text>]}
						optionsIOS={['取消', '退出登录']}
						onPress={(i) => { this.actionSheetPress(i) }}
						styles={{
							titleBox: {
								height: 63 * scale,
								marginBottom: 1 * scale
							}
						}}
					/>
				</View>
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	listBox: {
		backgroundColor: '#fff',
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale
	},
	list: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		borderBottomWidth: 1,
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		height: 52 * scale,
		width: '100%',
	},
	listActive: {
		borderBottomWidth: 0,
	},
	listLeft: {
		fontSize: 14 * scale,
		color: style.color.dark
	},
	listRight: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center'
	},
	listRightText: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
		marginRight: 8 * scale,
	},
	listRightImg: {
		width: 6 * scale,
		height: 11 * scale,
	},
	logOut: {
		width: '100%',
		height: 52 * scale,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: style.color.white,
		marginTop: 57 * scale
	},
	switchEnviromentButton: {
		width: '100%',
		height: 52 * scale,
		flexDirection: 'column',
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: style.color.white,
		marginTop: 10 * scale
	},
	logOutText: {
		fontSize: 14 * scale,
		color: style.color.dark,
	},
	logOutTextColor: {
		color: '#FF3B30',
		fontSize: 20 * scale
	},
	sheetTextColor: {
		color: style.color.themeColor,
		fontSize: 20 * scale,
	},
	actionTitle: {
		width: 220 * scale,
		fontSize: 13 * scale,
		textAlign: 'center',
		lineHeight: 18 * scale
	},
	enviroment: {
		width: '100%',
		height: 52 * scale,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		marginTop: 20 * scale
	},
	enviromentText: {
		color: style.color.themeColor,
		fontSize: 18 * scale
	}
})